import React, { useState, useEffect } from 'react';
import { Layout, Table, Typography, Tag, Button, Space, Spin, message, Select, Empty, DatePicker } from 'antd';
import { useNavigate } from 'react-router-dom';
import { ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { fetchTrades } from '../services/api';

const { Content } = Layout;
const { Title, Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

/**
 * 交易历史页面
 * 
 * 功能：
 * - 展示用户的交易历史记录
 * - 支持按交易状态筛选
 * - 支持按时间范围筛选
 * - 支持按交易类型（买入/卖出）筛选
 * - 提供交易详情查看入口
 */
const TradeHistory = () => {
  const [trades, setTrades] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    status: '',
    type: '',
    dateRange: null
  });
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  const navigate = useNavigate();

  // 交易状态配置
  const statusConfig = {
    pending: { text: '待付款', color: 'orange', icon: <ClockCircleOutlined /> },
    paid: { text: '已付款', color: 'blue', icon: <ClockCircleOutlined /> },
    shipped: { text: '已发货', color: 'green', icon: <CheckCircleOutlined /> },
    completed: { text: '已完成', color: 'green', icon: <CheckCircleOutlined /> },
    cancelled: { text: '已取消', color: 'gray', icon: <CloseCircleOutlined /> },
    refunded: { text: '已退款', color: 'red', icon: <ExclamationCircleOutlined /> }
  };

  // 加载交易数据
  const loadTrades = async (page = 1, filterOptions = filters) => {
    setLoading(true);
    try {
      const params = {
        page,
        page_size: pagination.pageSize,
        status: filterOptions.status || undefined,
        type: filterOptions.type || undefined,
        start_date: filterOptions.dateRange?.[0]?.format('YYYY-MM-DD'),
        end_date: filterOptions.dateRange?.[1]?.format('YYYY-MM-DD')
      };

      const response = await fetchTrades(params);
      setTrades(response.items);
      setPagination(prev => ({
        ...prev,
        current: page,
        total: response.total
      }));
    } catch (error) {
      message.error('加载交易历史失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理状态筛选
  const handleStatusFilter = (value) => {
    setFilters(prev => ({ ...prev, status: value }));
    loadTrades(1, { ...filters, status: value });
  };

  // 处理类型筛选
  const handleTypeFilter = (value) => {
    setFilters(prev => ({ ...prev, type: value }));
    loadTrades(1, { ...filters, type: value });
  };

  // 处理日期范围筛选
  const handleDateRangeFilter = (dates) => {
    setFilters(prev => ({ ...prev, dateRange: dates }));
    loadTrades(1, { ...filters, dateRange: dates });
  };

  // 处理分页变化
  const handlePageChange = (page) => {
    loadTrades(page);
  };

  // 查看交易详情
  const handleViewTrade = (tradeId) => {
    navigate(`/trades/${tradeId}`);
  };

  // 查看商品详情
  const handleViewProduct = (productId) => {
    navigate(`/products/${productId}`);
  };

  // 表格列配置
  const columns = [
    {
      title: '交易编号',
      dataIndex: 'id',
      key: 'id',
      render: (id) => <Text code>{id}</Text>
    },
    {
      title: '商品信息',
      dataIndex: 'product',
      key: 'product',
      render: (product) => (
        <Space onClick={() => handleViewProduct(product.id)} style={{ cursor: 'pointer' }}>
          <Text strong>{product.title}</Text>
          <Tag color="blue">¥{product.price}</Tag>
        </Space>
      )
    },
    {
      title: '交易类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => (
        <Tag color={type === 'buy' ? 'green' : 'orange'}>
          {type === 'buy' ? '买入' : '卖出'}
        </Tag>
      )
    },
    {
      title: '交易金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => <Text strong>¥{amount}</Text>
    },
    {
      title: '交易状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const config = statusConfig[status];
        return (
          <Tag icon={config.icon} color={config.color}>
            {config.text}
          </Tag>
        );
      }
    },
    {
      title: '交易时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleViewTrade(record.id)}>
            查看详情
          </Button>
          {record.status === 'pending' && record.type === 'buy' && (
            <Button type="primary">立即付款</Button>
          )}
          {record.status === 'paid' && record.type === 'sell' && (
            <Button type="primary">发货</Button>
          )}
          {record.status === 'shipped' && record.type === 'buy' && (
            <Button type="primary">确认收货</Button>
          )}
        </Space>
      )
    }
  ];

  // 初始化加载
  useEffect(() => {
    loadTrades();
  }, []);

  return (
    <Layout className="trade-history-layout">
      <Content className="trade-history-content">
        <Title level={3} className="page-title">交易历史</Title>
        
        {/* 筛选工具栏 */}
        <div className="filter-toolbar">
          <Space size="middle" wrap>
            <Select
              placeholder="交易状态"
              allowClear
              style={{ width: 150 }}
              onChange={handleStatusFilter}
              value={filters.status}
            >
              {Object.entries(statusConfig).map(([key, config]) => (
                <Option key={key} value={key}>
                  <Tag icon={config.icon} color={config.color}>
                    {config.text}
                  </Tag>
                </Option>
              ))}
            </Select>
            
            <Select
              placeholder="交易类型"
              allowClear
              style={{ width: 120 }}
              onChange={handleTypeFilter}
              value={filters.type}
            >
              <Option value="buy">买入</Option>
              <Option value="sell">卖出</Option>
            </Select>
            
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              onChange={handleDateRangeFilter}
              value={filters.dateRange}
            />
          </Space>
        </div>
        
        {/* 交易记录表格 */}
        <div className="trades-table">
          {loading ? (
            <div className="loading-container">
              <Spin size="large" />
            </div>
          ) : trades.length > 0 ? (
            <Table
              columns={columns}
              dataSource={trades}
              rowKey="id"
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: pagination.total,
                onChange: handlePageChange
              }}
              className="trade-table"
            />
          ) : (
            <Empty description="暂无交易记录" className="empty-container" />
          )}
        </div>
      </Content>
    </Layout>
  );
};

export default TradeHistory;
